<?php
App::uses('AuthComponent', 'Controller/Component');
class Article extends AppModel {
	public $name = 'Article';

	public $hasMany = array('Comment');

	public $belongsTo = array('User');
	public $hasAndBelongsToMany = array(
		'Category' => array(
			'className' => 'Category',
			'joinTable' => 'group_categories',
			'foreignKey' => 'article_id',
			'associationForeignKey' => 'category_id',
		)
	);

	public $validate = array(
			'title' => array('rule' => 'notEmpty'),
			'body' => array('rule' => 'notEmpty')
	);


	public function isOwnedBy($articleId, $userId, $access) {
		if($access === "3"){
			return true;
		}elseif($access === "2"){
			// @todo find a more elegant way to do this

			Controller::loadModel('Role');

			$this->id = $articleId;
			$articleAccess = $this->Role->field('access', array('id' => $this->User->field('role_id', array('id' => $this->field('user_id')))));

			if($this->field('id', array('id' => $articleId, 'user_id' => $userId)) === $articleId){
				return true;
			}else{
				return ($access > $articleAccess) ? true : false;
			}
		}elseif($access === "1"){
			return $this->field('id', array('id' => $articleId, 'user_id' => $userId)) === $articleId;
		}
	}

	public function beforeSave(){
		return true;
	}

}